package com.sixuerain.heartkey.db.dao;

import java.util.ArrayList;
import java.util.List;

import com.sixuerain.heartkey.db.helper.DatabaseHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class BaseDAO {
	
	private DatabaseHelper dbHelper = null;
	
	public BaseDAO(Context context) {
		dbHelper = DatabaseHelper.getInstance(context);
	}
	
	public SQLiteDatabase getDB(boolean isWrite) {
		if(isWrite)
			return dbHelper.getWritableDatabase();
		else
			return dbHelper.getReadableDatabase();
	}
	
	public Object singleSearch(String table,
			String[] columns, String selection, String[] selectionArgs,
			String groupBy, String having, String orderBy, String limit) {
		Object object = null;

		final Cursor cursor = this.getDB(false).query(table, columns, selection,
				selectionArgs, groupBy, having, orderBy, limit);
		try {
			if (cursor.moveToFirst()) {
				object = this.mapRow(cursor, cursor.getCount());
			}
		} finally {
			cursor.close();
		}
		return object;
	}
	
	public List multiSearch(String table,
			String[] columns, String selection, String[] selectionArgs,
			String groupBy, String having, String orderBy, String limit) {
		List list = new ArrayList();

		final Cursor cursor = this.getDB(false).query(table, columns, selection,
				selectionArgs, groupBy, having, orderBy, limit);
		try {
			while (cursor.moveToNext()) {
				list.add(this.mapRow(cursor, 1));
			}
		} finally {
			cursor.close();
		}
		return list;
	}
	
	public int update(String table,ContentValues values
			,String whereClause,String[] whereArgs) {
		return this.getDB(true).update(table, values, whereClause, whereArgs);
	}
	
	public int updateByField(String table,ContentValues values,String field,String fieldValue) {
		return this.update(table, values,
				field + "=?", new String []{fieldValue});
	}
	
	/**
	 * delete data by a field
	 * @param table
	 * @param field
	 * @param value
	 * @return
	 */
	public int deleteByField(String table, String field, String value) {
		return this.getDB(true).delete(table, field + "=?", new String[] { value });
	}
	
	public int deleteByFields(String table, String whereClause, String[] whereArgs) {
		return this.getDB(true).delete(table, whereClause, whereArgs);
	}


	
	public long insert(String table,ContentValues values) {
		return this.getDB(true).insert(table, null, values);

	}
	
	public void executeSQL(String sql,List params) {
		this.getDB(true).execSQL(sql, params.toArray());
	}
	
	public abstract Object mapRow(Cursor cursor, int rowNum);
	
	
	
	

}
